package com.jzsm.modules.sender.senderService.impl.dingtalk;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.jzsm.modules.sender.bo.message.MessageBo;
import com.jzsm.modules.sender.enums.ChannelTypeEnum;
import com.jzsm.common.annotation.Channel;
import com.jzsm.common.utils.AssertUtils;
import com.jzsm.modules.sender.pojo.PushChannelAccount;
import com.jzsm.modules.sender.bo.accountConfig.RobotConfigBo;
import com.jzsm.modules.sender.senderService.AbstractMessageSender;
import com.taobao.api.ApiException;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import org.springframework.stereotype.Component;

/**
 * 钉钉机器人 渠道
 */
@Channel(ChannelTypeEnum.DingtalkRobot)
@Component
@FieldDefaults(level = AccessLevel.PRIVATE)
public class DingtalkRobotMessageSender extends AbstractMessageSender {

    @Override
    public String sendMessage(String message, PushChannelAccount account) {
        return run(message, account);
    }

    @Override
    public String sendMessage(MessageBo messageBo) {
        return run(messageBo.getMessage(), messageBo.getAccount());
    }

    private String run(String message, PushChannelAccount account) {
        RobotConfigBo configBo = getConfigBo(account);
        checkAccountConfig(configBo);
        String webhook = configBo.getWebhook();
        DingTalkClient client = new DefaultDingTalkClient(webhook);
        OapiRobotSendRequest request = JSON.parseObject(message, OapiRobotSendRequest.class);
        OapiRobotSendResponse response = null;
        try {
            response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
            AssertUtils.throwError(e.getMessage());
        }
        if (!response.isSuccess()) {
            AssertUtils.throwError(JSON.toJSONString(response));
        }
        return response.getBody();
    }

    private RobotConfigBo getConfigBo(PushChannelAccount account) {
        String accountConfig = account.getAccountConfig();
        return JSON.parseObject(accountConfig, RobotConfigBo.class);
    }

    private void checkAccountConfig(RobotConfigBo configBo) {
        AssertUtils.isNotBlank("webhook 参数不允许为空！", configBo.getWebhook());
    }

}
